import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:opnvpn_flutter/opnvpn_flutter.dart';
import 'package:opnvpn_flutter_example/data_source.dart';
import 'package:opnvpn_flutter_example/server_list.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: '',
        theme: ThemeData(primaryColor: Colors.amber),
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),
          ),
          body: App(),
        ));
  }
}

class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<App> {
  late OpenVPN engine;
  VpnStatus? status;
  VPNStage? stage;
  bool _granted = false;

  @override
  void initState() {
    engine = OpenVPN(
      onVpnStatusChanged: (data) {
        setState(() {
          status = data;
          debugPrint(data?.byteIn ?? '====');
        });
      },
      onVpnStageChanged: (data, raw) {
        setState(() {
          debugPrint(data?.name ?? '====');
          stage = data;
        });
      },
    );

    engine.initialize(
      groupIdentifier: "group.com.laskarmedia.vpn",
      providerBundleIdentifier:
          "id.laskarmedia.openvpnFlutterExample.VPNExtension",
      localizedDescription: "VPN by Nizwar",
      lastStage: (stage) {
        setState(() {
          this.stage = stage;
        });
      },
      lastStatus: (status) {
        setState(() {
          this.status = status;
        });
      },
    );
    super.initState();
  }

  Future<void> initPlatformState() async {
    var config = DataSource.mServerConfig;
    engine.connect(config?.ovpnConfiguration ?? '', config?.serverName ?? '',
        username: config?.vpnUserName,
        password: config?.vpnPassword,
        certIsRequired: true);
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(stage?.toString() ?? VPNStage.disconnected.toString()),
            Text(status?.toJson().toString() ?? ""),
            TextButton(
              child: const Text("Start"),
              onPressed: () {
                initPlatformState();
              },
            ),
            TextButton(
                onPressed: () {
                  // 在按钮点击时跳转到另一个页面
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => ServerListPage()),
                  );
                },
                child: const Text("choose server")),
            TextButton(
              child: const Text("stop"),
              onPressed: () {
                engine.disconnect();
              },
            ),
            if (Platform.isAndroid)
              TextButton(
                child: Text(_granted ? "Granted" : "Request Permission"),
                onPressed: () {
                  engine.requestPermissionAndroid().then((value) {
                    setState(() {
                      debugPrint("授权 $value");
                      _granted = value;
                    });
                  });
                },
              ),
          ],
        ),
      ),
    );
  }
}

const String defaultVpnUsername = "";
const String defaultVpnPassword = "";

String config = "YOUR OPENVPN CONFIG HERE";
